package com.ssyu.examination.system.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.ssyu.examination.conmmon.App;
import com.ssyu.examination.conmmon.AppServlet;
import com.ssyu.examination.conmmon.Constants;
import com.ssyu.examination.conmmon.PageModel;
import com.ssyu.examination.conmmon.util.DBUtil;
import com.ssyu.examination.conmmon.util.DateUtil;
import com.ssyu.examination.conmmon.util.FastjsonUtil;
import com.ssyu.examination.conmmon.util.MD5Util;
import com.ssyu.examination.system.entity.ClazzEntity;
import com.ssyu.examination.system.entity.RoleEntity;
import com.ssyu.examination.system.entity.SystemEntiy;
import com.ssyu.examination.system.service.SystemService;

@WebServlet("/SystemServlet")
public class SystemServlet extends AppServlet {

	private static final long serialVersionUID = 1L;

	public SystemServlet() {
		super();
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("login".equals(command)) {
			login(request, response);
		} else if ("checkPassword".equals(command)) {
			checkPassword(request, response);
		} else if ("checkPhone".equals(command)) {
			checkPhone(request, response);
		} else if ("checkEmail".equals(command)) {
			checkEmail(request, response);
		} else if ("updatePassword".equals(command)) {
			updatePassword(request, response);
		} else if ("userTable".equals(command)) {
			userTable(request, response);
		} else if ("adduser".equals(command)) {
			adduser(request, response);
		} else if ("updateInfo".equals(command)) {
			updateInfo(request, response);
		} else if ("logout".equals(command)) {
			logout(request, response);
		} else if ("getuser".equals(command)) {
			getuser(request, response);
		} else if ("updateUser".equals(command)) {
			updateUser(request, response);
		} else if ("replacement".equals(command)) {
			replacement(request, response);
		} else if ("updateStateUser".equals(command)) {
			updateStateUser(request, response);
		} else if ("checkEmailSystem".equals(command)) {
			checkEmailSystem(request, response);
		} else if ("checkPhoneSystem".equals(command)) {
			checkPhoneSystem(request, response);
		} else if ("checkCodeSystem".equals(command)) {
			checkCodeSystem(request, response);
		}
	}

	/**
	 * 验证账号是否存在
	 * 
	 * @param request
	 * @param response
	 */
	private void checkCodeSystem(HttpServletRequest request,
			HttpServletResponse response) {
		String code = request.getParameter("code");
		SystemServlet systemServlet = DBUtil.getUniqueResult(
				SystemServlet.class, "select * from sys_user where code=?",
				code);
		if (systemServlet == null) {
			print(response, true);
		}
	}

	/**
	 * 验证电话是否存在
	 * 
	 * @param request
	 * @param response
	 */
	private void checkPhoneSystem(HttpServletRequest request,
			HttpServletResponse response) {
		String phone = request.getParameter("phone");
		SystemServlet systemServlet = DBUtil.getUniqueResult(
				SystemServlet.class, "select * from sys_user where phone=?",
				phone);
		if (systemServlet == null) {
			print(response, true);
		}

	}

	/**
	 * 查看email是否存在
	 * 
	 * @param request
	 * @param response
	 */
	private void checkEmailSystem(HttpServletRequest request,
			HttpServletResponse response) {
		String email = request.getParameter("email");
		SystemServlet systemServlet = DBUtil.getUniqueResult(
				SystemServlet.class, "select * from sys_user where email=?",
				email);
		if (systemServlet == null) {
			print(response, true);
		}
	}

	/**
	 * 修改权限
	 * 
	 * @param request
	 * @param response
	 */
	private void updateStateUser(HttpServletRequest request,
			HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		SystemEntiy systemEntiy = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where id=?", id);
		String state = systemEntiy.getState();
		if (state.equals("启用")) {
			state = "2";
		} else {
			state = "1";
		}
		int row = DBUtil.executeUpdate(
				"update sys_user set state=? where id=? ", state, id);
		if (row == 1) {
			print(response, 1);
		}
	}

	/**
	 * 设置初始密码
	 * 
	 * @param request
	 * @param response
	 */
	private void replacement(HttpServletRequest request,
			HttpServletResponse response) {
		String ids = request.getParameter("ids");
		int row = DBUtil
				.executeUpdate("UPDATE sys_user SET password=MD5(123456)  WHERE id IN ("
						+ ids + ")");

		if (row >= 1) {
			print(response, 1);
		}
	}

	/**
	 * 修改信息
	 * 
	 * @param request
	 * @param response
	 */
	private void updateUser(HttpServletRequest request,
			HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String className = request.getParameter("class__name");
		String operateTime = DateUtil.format(new Date());
		SystemEntiy systemPhone = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where phone=? and id !=?", phone, id);
		SystemEntiy systemEmail = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where email=? and id !=?", email, id);
		if (systemPhone == null && systemEmail == null) {
			if (className != null) {
				int classId = DBUtil.getUniqueResult(ClazzEntity.class,
						"select * from sys_class where name=?", className)
						.getId();
				int row = DBUtil
						.executeUpdate(
								"UPDATE sys_user SET phone=?,email=?,operate_time=?,class_id=? where id=?",
								phone, email, operateTime, classId, id);
				if (row == 1) {
					print(response, 1);
				}
			} else {
				int row = DBUtil
						.executeUpdate(
								"UPDATE sys_user SET phone=?,email=?,operate_time=?,class_id=? where id=?",
								phone, email, operateTime, 0, id);
				if (row == 1) {
					print(response, 1);
				}
			}
		} else {
			print(response, null);
		}

	}

	/**
	 * 查询当前id的信息（修改时用）
	 * 
	 * @param request
	 * @param response
	 */
	private void getuser(HttpServletRequest request,
			HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		SystemEntiy systemEntiy = DBUtil
				.getUniqueResult(
						SystemEntiy.class,
						"select sys_user.*,sys_class.name as class__name FROM sys_user,sys_class where sys_user.class_id=sys_class.id AND sys_user.id=?",
						id);
		if (systemEntiy != null) {
			print(response, FastjsonUtil.toJson(systemEntiy));
		} else {
			systemEntiy = DBUtil.getUniqueResult(SystemEntiy.class,
					"select * FROM sys_user where id=?", id);
			print(response, FastjsonUtil.toJson(systemEntiy));
		}
	}

	/**
	 * 新增用户
	 * 
	 * @param request
	 * @param response
	 */
	private void adduser(HttpServletRequest request,
			HttpServletResponse response) {
		// List<Object> list = new ArrayList<>();

		int id = App.getOperateId(request, response);
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String roleName = request.getParameter("role__name");
		String classname = request.getParameter("class__name");
		RoleEntity roleEntity = DBUtil.getUniqueResult(RoleEntity.class,
				"SELECT id,name FROM sys_role where name=?", roleName);
		ClazzEntity clazzEntity = DBUtil.getUniqueResult(ClazzEntity.class,
				"SELECT id,name FROM sys_class where name=?", classname);
		String createTime = DateUtil.format(new Date());
		String operateTime = DateUtil.format(new Date());
		int roleId = roleEntity.getId();
		int clazzId = clazzEntity.getId();

		/**
		 * 做唯一验证
		 */
		SystemEntiy systemCode = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where code=?", code);
		SystemEntiy systemPhone = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where phone=?", phone);
		SystemEntiy systemEmail = DBUtil.getUniqueResult(SystemEntiy.class,
				"select * from sys_user where email=?", email);
		if (systemCode == null && systemPhone == null && systemEmail == null) {
			List<Object> list = new ArrayList<>();

			list.add(code);
			list.add(MD5Util.md5(password));
			list.add(name);
			list.add(sex);
			list.add(phone);
			list.add(email);
			list.add(createTime);
			list.add(id);
			list.add(operateTime);
			list.add(roleId);
			list.add(clazzId);
			list.add(1);
			int row = DBUtil
					.executeUpdate(
							"INSERT INTO sys_user VALUES(NULL, ?, ?, ?, ?, ?, ?, ? , ?, ?, ?, ?, ?, NULL)",
							list);

			if (row == 1) {
				print(response, 1);
			}
		}

	}

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		SystemService systemService = new SystemService();

		SystemEntiy systemEntiy = systemService.login(code,
				MD5Util.toMD5(password));
		if (systemEntiy == null) {
			request.setAttribute("flag", "fail");
			request.getRequestDispatcher("/login.jsp").forward(request,
					response);
		} else {
			systemEntiy = systemService.loginState(code,
					MD5Util.toMD5(password));
			if (systemEntiy == null) {
				request.setAttribute("flag", "failState");
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
			} else {
				request.getSession().setAttribute("systemEntiy", systemEntiy);
				request.getRequestDispatcher("/view/common/index.jsp").forward(
						request, response);
			}
		}
	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getSession().invalidate();
		request.getRequestDispatcher("/login.jsp").forward(request, response);
	}

	/**
	 * AJAX得到原密码,检查与原密码是否一致
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void checkPassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		SystemService systemService = new SystemService();

		SystemEntiy systemEntiy = systemService.checkPassword(code,
				MD5Util.toMD5(password));
		if (systemEntiy == null) {
			response.getWriter().print(1);
		}

	}

	/**
	 * AJAX得到电话号码,检查电话号码是否存在
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */

	private void checkPhone(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String phone = request.getParameter("phone");
		SystemService systemService = new SystemService();

		SystemEntiy systemEntiy = systemService.checkPhone(code, phone);
		if (systemEntiy != null) {
			response.getWriter().print(1);
		}

	}

	/**
	 * AJAX得到邮箱,检查邮箱是否存在
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void checkEmail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String email = request.getParameter("email");
		SystemService systemService = new SystemService();

		SystemEntiy systemEntiy = systemService.checkEmail(code, email);
		if (systemEntiy != null) {
			response.getWriter().print(1);
		}

	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		SystemService systemService = new SystemService();
		int reslut = systemService
				.updatePassword(code, MD5Util.toMD5(password));
		if (reslut != 0) {
			response.getWriter().print(1);
		}
	}

	/**
	 * 增加初始数据表格
	 * 
	 * 这里的left join 与条件查询除了问题
	 * 
	 * @param request
	 * @param response
	 */
	private void userTable(HttpServletRequest request,
			HttpServletResponse response) {
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");

		String userToolbarName = request.getParameter("userToolbarName");
		String userToolbarClassName = request
				.getParameter("userToolbarClassName");
		/* String userToolbarTime = request.getParameter("userToolbarTime"); */
		List<Object> systemList = new ArrayList<>();
		StringBuilder sql = new StringBuilder(
				"select sys_user.id,sys_user.code,sys_user.name,sys_user.sex,sys_user.phone,sys_user.email,sys_user.create_time,sys_role.name as role__name,sys_class.name as class__name,sys_user.state,sys_user.memo FROM sys_role,sys_user,sys_class where sys_user.class_id=sys_class.id and sys_user.role_id=sys_role.id ");
		if (StringUtils.isNotBlank(userToolbarName)) {
			sql.append("and sys_user.name like ? ");
			systemList.add("%" + userToolbarName + "%");
			System.out.println(userToolbarName);
		}
		if (StringUtils.isNotBlank(userToolbarClassName)) {
			sql.append("and sys_class.name like ? ");
			systemList.add("%" + userToolbarClassName + "%");
		}
		sql.append("ORDER BY ");
		sql.append(sort);
		sql.append(" ");
		sql.append(order);
		sql.append(" LIMIT ?,?");
		/*
		 * if (userToolbarTime != null) {
		 * sql.append("and sys_user.name like ? "); }
		 */
		systemList.add((page - 1) * rows);
		systemList.add(rows);
		PageModel<SystemEntiy> user = DBUtil.executeQueryByPage(
				SystemEntiy.class, sql.toString(), systemList);
		print(response,
				FastjsonUtil.toJsonWithDateFormat(user, "yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 查询menu
	 */
	/*
	 * else if ("userGread".equals(command)) { userGread(request, response); }
	 * private void userGread(HttpServletRequest request, HttpServletResponse
	 * response) { int id = 0; String idStr = request.getParameter("id"); if
	 * (idStr != null) { id = Integer.parseInt(idStr); }
	 * 
	 * List<MenuEntity> menuList = DBUtil.executeQuery(MenuEntity.class,
	 * "SELECT * FROM menu WHERE pid=?", id);
	 * 
	 * print(response, FastjsonUtil.toJson(menuList)); }
	 */

	/**
	 * 查询个人信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updateInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		SystemService systemService = new SystemService();

		int reslut = systemService.personInfo(code, phone, email);
		if (reslut != 0) {
			response.getWriter().print(1);
		}
	}
}
